<?php

namespace app\admin\controller;

use app\common\model\News;
use app\common\model\NewsSite as NewsSiteModel;
use app\common\controller\AdminBase;

/**
 * 新闻来源管理
 * Class Category
 * @package app\admin\controller
 */
class NewsSite extends AdminBase
{

    protected $model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new NewsSiteModel();
    }

    /**
     * 新闻来源管理
     * @return mixed
     */
    public function index()
    {
        $sites = $this->model->select();
        $this->assign('list', $sites);
        return $this->fetch();
    }


    /**
     * 保存资源来源
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();

            $validateResult = $this->validate($data, 'SiteCate');
            if ($validateResult !== true) {

                return json(array('code' => 0, 'msg' => $validateResult, 'data' => []));

            } else {
                if ($this->model->allowField(true)->save($data)) {
                    return json(array('code' => 200, 'msg' => '添加成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '添加失败'));
                }
            }
        }
    }

    /**
     * 更新新闻来源
     * @param $id
     */
    public function update()
    {

        if ($this->request->isPost()) {
            $data            = $this->request->param();
            if ($this->model->allowField(true)->save($data, ['id' => $data['id']])) {

                return json(array('code' => 200, 'msg' => '修改成功'));
            } else {

                return json(array('code' => 0, 'msg' => '修改失败'));
            }
        }
    }

    /**
     * 删除来源
     * @param $id
     */
    public function delete($id)
    {
        if ($this->model->destroy($id)) {
            return json(array('code' => 200, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }
}